<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>如何在写await async的时候不用try catch</title>
</head>

<body>
  <script>
    function taskPromise(status) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (status === "fail") {
            return reject("error")
          } else {
            return resolve("success")
          }
        }, 1000)
      })
    }


    function to(promise) {
      return promise.then(data => {
        return [null, data];
      })
        .catch(err => [err]);
    }


    async function asyncTasks() {
      let err, result
      [err, result] = await to(taskPromise(""))
      if (err) {
        console.log("it‘s error")  
      } else {
        console.log("it‘s" + result) 
      }

      [err, result] = await to(taskPromise("fail"))
      if (err) {
        console.log("it‘s error")
      } else {
        console.log("it‘s" + result)
      }

    }

    asyncTasks()  //it‘ssuccess   it‘s error





  </script>

</body>

</html>